const Spu = require('../../models/product/spu.model');
const Attr = require('../../models/product/attr.model');
const SpuImage = require('../../models/product/spuImage.model');
const SpuSale = require('../../models/product/spuSale.model');
const Sku = require('../../models/product/sku.model');
const SkuAttr = require('../../models/product/skuAttr.model');
const SkuSaleAttr = require('../../models/product/skuSaleAttr.model');
// 引入sequelize
const sequelize = require('../../config/db')
// 引入发送响应函数
const sendResponse = require('../../utils/response');

// 获取某个分类的spu列表
exports.getSpuList = async (req, res, next) => {
  try {
    // 获取分页参数
    const page = parseInt(req.params.page, 10) || 1;
    const limit = parseInt(req.params.limit, 10) || 10;
    // 计算偏移量
    const offset = (page - 1) * limit;
    // 获取分类id
    const { category3Id } = req.query;
    if(!category3Id){
      return sendResponse(res, { code: 500, message: '参数错误' }) }
    // 获取商品列表
    const spuList = await Spu.findAndCountAll({
      limit,
      offset,
      where: { category3Id },
      order: [['id', 'DESC']],
      attributes: ['id', 'spuName', 'description', 'category3Id', 'tmId'],
      include: [{
        model: SpuImage, 
        as: 'spuImageList', 
        attributes: ['id', 'spuId','imgUrl', 'imgName', 'createTime', 'updateTime']
      }],
      distinct: true, // 确保正确计数主模型
    });
    // console.log(spuList.rows[2].dataValues.spuImageList);
    
    return sendResponse(res, { 
      data: { 
        records: spuList.rows,
        total: spuList.count, // 总条数
        size: limit,
        current: page,
        searchCount: true, // 搜索结果条数
        pages: Math.ceil(spuList.count / limit)
      }
    });
  }catch (error) {
    next(error)
  }
}

// 获取某个spu的图片列表
exports.getSpuImageList = async (req, res, next) => {
  try {
    const { spuId } = req.params;
    if(!spuId){
      return sendResponse(res, { code: 500, message: '参数错误' }) }
    const spuImageList = await SpuImage.findAll({
      where: { spuId },
      attributes: ['id', 'spuId','imgUrl', 'imgName', 'createTime', 'updateTime']
    });
    return sendResponse(res, { data: spuImageList });
  }catch (error) {
    next(error)
  }
}

// 获取某个spu的销售属性列表
exports.getSpuSaleAttrList = async (req, res, next) => {
  try{
    const { spuId } = req.params;
    if(!spuId){
      return sendResponse(res, { code: 500, message: '参数错误' }) }
    // 获取spu销售属性列表
    const spuSaleAttrList = await SpuSale.findAll({
      where: { spuId, saleAttrValueName: '' },
      attributes: ['id', 'spuId', 'baseSaleAttrId', 'saleAttrName', 'createTime', 'updateTime'],
      include: [{
        model: SpuSale,
        as: 'spuSaleAttrValueList',
        attributes: ['id', 'spuId', 'baseSaleAttrId', 'saleAttrName', 'saleAttrValueName', 'createTime', 'updateTime'],
      }],
      through: { attributes: [] }, // 去除中间表
      distinct: true, // 确保正确计数主模型
    });
    return sendResponse(res, { data: spuSaleAttrList });
  }catch(error){
    next(error)
  }
}

// 获取整个项目的全部销售属性列表
exports.getBaseSaleAttrList = async (req, res, next) => {
  try{
    const BaseSaleAttr = await Attr.findAll({
      attributes: ['id', ['attrName' , 'name']]
    })
    return sendResponse(res, { data: BaseSaleAttr });
  } catch(error){
    next(error)
  }
}

// 新增spu
exports.saveSpuInfo = async (req, res, next) => {
  const transaction = await sequelize.transaction();
  try{
    const {spuName, description, category3Id, tmId, spuSaleAttrList, spuImageList} = req.body;
    if(!spuName || !description || !category3Id || !tmId){
      return sendResponse(res, { code: 500, message: '参数错误' }) 
    }
    const spu = await Spu.create({
      spuName, description, category3Id, tmId
    }, {transaction})
    // 保存spu图片
    if(spuImageList && spuImageList.length > 0){
      spuImageList.forEach(async (item) => {
        console.log(item);
        
        await SpuImage.create({
          spuId: spu.id,
          imgUrl: item.imgUrl.url || item.imgUrl,
          imgName: item.imgName
        })
      })
    }
    // console.log(spuSaleAttrList[0]);
    // console.log(spuSaleAttrList[0].spuSaleAttrValueList);
    
    // 保存spu销售属性
    if(spuSaleAttrList?.length){
      for (const item of spuSaleAttrList) {
        // 保存spu销售属性
        const newSaleAttr = await SpuSale.create({
          spuId: spu.id,
          baseSaleAttrId: item.baseSaleAttrId,
          saleAttrName: item.saleAttrName,
          saleAttrValueName: ''
        }, { transaction })
        // 保存spu销售属性值
        if(item.spuSaleAttrValueList?.length){
          for(const item2 of item.spuSaleAttrValueList){
            await SpuSale.create({
              pid: newSaleAttr.id,
              spuId: spu.id,
              baseSaleAttrId: item2.baseSaleAttrId,
              saleAttrName: item.saleAttrName,
              saleAttrValueName: item2.saleAttrValueName
            }, { transaction })
          }
        }
      }
    }
    // 提交事务
    await transaction.commit();
    console.log('--------spu创建成功--------');
    
    return sendResponse(res, { message: "添加spu成功", data: spu });
  } catch(error){
    await transaction.rollback();
    console.error('SPU创建失败:', {
      error: error.message,
      stack: error.stack,
      requestBody: req.body
    });
    next(error.message)
  }
}

// 更新spu
exports.updateSpuInfo =  async (req, res, next) => {
  const transaction = await sequelize.transaction();
  try{
    const {id, spuName, description, category3Id, tmId, spuSaleAttrList, spuImageList} = req.body
    if(!id){
      return sendResponse(res, { code: 500, message: '参数错误' }) 
    }
    // 更新spu
    await Spu.update({
      spuName, description, category3Id, tmId
    }, { where: { id }, transaction })
    // 删除spu图片
    await SpuImage.destroy({ where: { spuId: id }, transaction })
    // 保存spu图片
    if(spuImageList && spuImageList.length > 0){
      spuImageList.forEach(async (item) => {
        await SpuImage.create({
          spuId: id,
          imgUrl: item.imgUrl.url || item.imgUrl,
          imgName: item.imgName
        })
      })
    }
    // 删除spu销售属性
    await SpuSale.destroy({ where: { spuId: id }, transaction })
    // 保存spu销售属性
    if(spuSaleAttrList?.length){
      for (const item of spuSaleAttrList) {
        // 保存spu销售属性
        const newSaleAttr = await SpuSale.create({
          spuId: id,
          baseSaleAttrId: item.baseSaleAttrId,
          saleAttrName: item.saleAttrName,
          saleAttrValueName: ''
        }, { transaction })
        // 保存spu销售属性值
        if(item.spuSaleAttrValueList?.length){
          for(const item2 of item.spuSaleAttrValueList){
            await SpuSale.create({
              pid: newSaleAttr.id,
              spuId: id,
              baseSaleAttrId: item2.baseSaleAttrId,
              saleAttrName: item.saleAttrName,
              saleAttrValueName: item2.saleAttrValueName
            }, { transaction })
          }
        }
      }
    }
    // 提交事务
    await transaction.commit();
    console.log('--------spu更新成功--------');
    
    return sendResponse(res, { data: '更新成功' });
  }catch(error){
    await transaction.rollback();
    console.error('SPU更新失败:', {
      error: error.message,
      stack: error.stack,
      requestBody: req.body
    });
    next(error.message)
  }
}

// 删除spu
exports.deleteSpu = async (req, res, next) => {
  const transaction = await sequelize.transaction();
  try{
    // 获取spuId
    const { spuId } = req.params;
    if(!spuId){
      return sendResponse(res, { code: 500, message: '参数错误' }) 
    }
    // 获取spu
    const spu = await Spu.findOne({ where: { id: spuId } });
    if(!spu){
      return sendResponse(res, { code: 500, message: 'spu不存在' }) 
    }
    // 删除spu
    await Spu.destroy({ where: { id: spuId }, transaction })
    // 删除spu图片
    await SpuImage.destroy({ where: { spuId }, transaction })
    // 删除spu销售属性
    await SpuSale.destroy({ where: { spuId }, transaction })
    // TODO删除sku
    // await Sku.destroy({ where: { spuId }, transaction })
    // 提交事务
    await transaction.commit();
    console.log('--------sku删除成功--------');
    return sendResponse(res, { message: '删除spu成功' });
  }catch(error){
    await transaction.rollback();
    console.error('SPU删除失败:', {
      error: error.message,
      stack: error.stack,
      requestBody: req.body
    });
    next(error)
  }
}

// 给某个spu添加一个sku
exports.saveSkuInfo = async (req, res, next) => {
  const transaction = await sequelize.transaction();
  try{
    const { 
      spuId, 
      category3Id, 
      tmId, 
      skuName, 
      skuDesc, 
      price, 
      weight, 
      skuDefaultImg, 
      skuAttrValueList, 
      skuSaleAttrValueList 
    } = req.body;
    if(!spuId || !category3Id || !tmId || !skuName || !price || !skuDefaultImg){
      return sendResponse(res, { code: 500, message: '参数错误' }) 
    }
    
    // console.log('sku:', req.body);
    // console.log('skuAttrValueList:', req.body.skuAttrValueList);
    // console.log('skuSaleAttrValueList:', req.body.skuSaleAttrValueList);
    
    // 保存sku 
    const createSku = await Sku.create({
      spuId,
      category3Id,
      tmId,
      skuName,
      skuDesc,
      price,
      weight,
      isSale: 0,
      skuDefaultImg
    }, { transaction });
    // 保存sku基本属性
    if(skuAttrValueList?.length){
      for(const item of skuAttrValueList){
        await SkuAttr.create({
          skuId: createSku.id,
          attrId: item.attrId,
          valueId: item.valueId,
          valueName: item.valueName
        }, { transaction })
      }
    }
    // 保存sku销售属性
    if (skuSaleAttrValueList?.length) {
      for (const item of skuSaleAttrValueList) {
        await SkuSaleAttr.create({
          skuId: createSku.id,
          saleAttrId: item.saleAttrId,
          saleAttrValueId: item.saleAttrValueId,
          saleAttrValueName: item.saleAttrValueName
        }, { transaction })
      }
    }
    // 提交事务
    await transaction.commit();
    console.log('--------sku添加成功--------');
    
    return sendResponse(res, { data: '添加sku' });
  }catch(error){
    await transaction.rollback();
    console.error('添加sku失败:', {
      error: error.message,
      stack: error.stack,
      requestBody: req.body
    });
    next(error)
  }
}

// 查看某个spu下的sku列表
exports.getSkuList = async (req, res, next) => {
  try{
    const { spuId } = req.params;
    if(!spuId){
      return sendResponse(res, { code: 500, message: '参数错误' }) 
    }
    const skuList = await Sku.findAll({ where: { spuId } });
    if(!skuList){
      return sendResponse(res, { code: 500, message: 'sku列表不存在' }) 
    }
    return sendResponse(res, { data: skuList });
  } catch(error){
    next(error)
  }
  sendResponse(res, { data: '查看sku列表' });
}
